package com.zrb.mobile.common;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.nostra13.universalimageloader.cache.memory.MemoryCacheAware;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import com.zrb.applib.utils.FileUtil;
 

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

/**
 * ͼƬ�첽������
 * 
 * @author Leslie.Fang
 * 
 */
public class LoadUserAvatar {
    // ����߳���
    //private static final int MAX_THREAD_NUM = 5;
    // һ���ڴ滺����� LruCache
    private  MemoryCacheAware<String, Bitmap>  bitmapCache;
    // �����ļ�����
  //  private FileUtil fileUtil;
 
    public static final String AvatarDir="/contentImg";
    // �̳߳�
    // private ExecutorService threadPools = null;
  
    public static String getAvatarpath(){
    	return FileUtil.filePath+AvatarDir;
    }
    
    public static String getAvatardir(){
    	return AvatarDir;
    }
    //local_image_path /imgpath
    public LoadUserAvatar(Context context) {
       // bitmapCache = new BitmapCache();
       // fileUtil = new FileUtil(context, local_image_path);
        ImageLoader imageLoader = ImageLoader.getInstance();
        bitmapCache=imageLoader.getMemoryCache();
    	 
       // threadPools = Executors.newFixedThreadPool(MAX_THREAD_NUM); 
    }
    

    public LoadUserAvatar() {
         ImageLoader imageLoader = ImageLoader.getInstance();
         bitmapCache=imageLoader.getMemoryCache();
     }
    
    @SuppressLint("HandlerLeak")
    public Bitmap loadImage(final ImageView imageView, final String imageUrl,
            final ImageDownloadedCallBack imageDownloadedCallBack) {
        final String filename = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        final String filepath = FileUtil.filePath+""+AvatarDir+"/"+ filename;

       // �ȴ��ڴ�����
     
       final String Cachekey= imageUrl+"_40x40";
        Bitmap bitmap = bitmapCache.get(Cachekey);//.getBitmap(imageUrl);
        if (bitmap != null) {
            Log.i("aaaa", "image exists in memory");
            return bitmap;
        }
      
        // ���ļ�����
        if (FileUtil.isBitmapExists(AvatarDir,filename)) {
            Log.i("aaaa", "image exists in file" + filename);

             bitmap = BitmapFactory.decodeFile(filepath);
            // �Ȼ��浽�ڴ�
            bitmapCache.put(Cachekey, bitmap);
            return bitmap;
        }

        // �ڴ���ļ��ж�û���ٴ���������
        if (imageUrl != null && !imageUrl.equals("")) {
            final Handler handler = new Handler() {
                @SuppressLint("HandlerLeak")
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 111 && imageDownloadedCallBack != null) {
                        Bitmap bitmap = (Bitmap) msg.obj;
                        imageDownloadedCallBack.onImageDownloaded(imageView, bitmap);
                    }
                }
            };

            Thread thread = new Thread() {
                @SuppressLint("NewApi")
                @Override
                public void run() {
                    Log.i("aaaa", Thread.currentThread().getName()+ " is running");
                    
                    InputStream inputStream =  getStream(imageUrl);
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = false;
                    options.inSampleSize = 1; // width��hight��Ϊԭ����ʮ��һ
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);

                    // ͼƬ���سɹ��󻺴沢ִ�лص�ˢ�½���
                    if (bitmap != null) {
                       // �Ȼ��浽�ڴ�
                         bitmapCache.put(Cachekey, bitmap);
                        // ���浽�ļ�ϵͳ
                       // fileUtil.saveBitmap(filename, bitmap);
                        FileUtil.saveBitmap(AvatarDir,filename, bitmap);
                        
                        Message msg = new Message();
                        msg.what = 111;
                        msg.obj = bitmap;
                        handler.sendMessage(msg); 

                    }
                }
            };
             thread.start();
            //threadPools.execute(thread);
        }

        return null;
    }

    private InputStream getStream(String url) {
        HttpParams httpparams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpparams, 30000);
        HttpClient client = new DefaultHttpClient(httpparams);
        HttpGet get = new HttpGet(url);

        try {
            HttpResponse response = client.execute(get);
            int status = response.getStatusLine().getStatusCode();

            if (200 == status) {
                return response.getEntity().getContent();
            }
        } catch (Exception e) {
            Log.i("TAG", e.getMessage());
        }

        return null;
    }
    /**
     * ͼƬ������ɻص��ӿ�
     * 
     */
    public interface ImageDownloadedCallBack {
        void onImageDownloaded(ImageView imageView, Bitmap bitmap);
    }

   
 
}
